<template>
  <div class="videoPage">
    <!-- 1.顶部导航栏 -->
    <Nav :data="form" />
    <!-- 2. 视频播放 -->
    <div :class="['videoPlayer',iswheel?'videoPlayerSmall':'']">
      <!-- <video id="media" src="@/assets/3copy.mp4" controls >
            <source src="@/assets/新录音.mp4" type="video/mp4">
            <source src="http://10.31.3.212:81/record/www/2024/01/16/219b4534-2cbc-422c-8ba1-c1382d89f3ce.mp4">
        </video> -->
      <div id="video-player"></div>
    </div>
    <!-- 3.文字记录/搜索 -->
    <div class="top">
      <h3>文字记录</h3>
      <div class="search">
        <el-input
          v-model="inputValue"
          class="w-50 m-2"
          placeholder="搜索"
          :prefix-icon="Search"
          @input="inputChange"
          :clearable="true"
        >
          <template #suffix>
            <span v-if="inputValue">{{count}}</span>
          </template>
        </el-input>
      </div>
    </div>
    <!-- 4.文字记录信息 -->
    <div class="transcriptionRecord">
      <el-scrollbar height="calc(100vh - 261px)" ref="scrollbarRef">
        <template v-if="list.length>0">
          <div class="recordinfo" v-for="(item, i) in list" :key="i" :id="'scroll_' + item.id">
            <!-- 1.左侧 -->
            <!-- <div class="left">
              <div>{{ item.userName.slice(-2) }}</div>
            </div> -->
            <!-- 2.右侧 -->
            <div class="right">
              <!-- 2.1 上层 -->
              <div class="rightTop">
                <!-- <span>{{ item.userName }}</span> -->
                <span>说话人</span>
                <span>{{ getHMS(item.startTime) }}</span>
              </div>
              <!-- 2.2 文字转写内容 currentTime-->
              <div
                v-html="item.content"
                class="rightContent"
                :class="[
                  currentTime * 1000 >= item.startTime && currentTime * 1000 < item.endTime
                    ? 'active'
                    : ''
                ]"
                @click="reversePosition(item)"
              ></div>
            </div>
          </div>
        </template>
        <div v-else style="text-align:center;color:lightgray;margin-top: 10px;">无文字记录</div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import Nav from '@/components/Nav.vue'
import { ref, onMounted, computed, onBeforeUnmount} from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useRoute} from 'vue-router'
const route = useRoute()
// import videoSrc from "@/assets/新录音_0822.mp3"
import videoSrc from '@/assets/cat.mp4'
// import videoSrc from '@/assets/adiao.mp4'

// import Player from 'xgplayer'
// import 'xgplayer/dist/index.min.css'
// import FlvPlayer from "xgplayer-flv"

import { request } from '@/utils/server.js'

import forwordimg from '@/assets/my_content/foward.png'
import rewindimg from '@/assets/my_content/rewind.png'

// porps父传子 defineProps接参
const form = {
  id: route.query.id,
  title: route.query.title,
  createdTime: route.query.createdTime,
  totalTime: route.query.totalTime,
  userName: route.query.userName,
  url: route.query.url,
  inputValue:route.query.inputValue

}

// 1.----会议记录（转文字）接口-----
const getConferenceList = () => {
  request
    .get('/sweet-api/conference/list/' + route.query.id)
    .then((res) => {
      // debugger
      // console.log("会议记录获取成功",res.data);
      if (res.data.code == 1) {
        originList.value = res.data.data
      }
    })
    .catch((error) => {
      console.log('会议记录获取失败', error)
    })
}

// 2.----添加到主页接口-----
const addToMainPage = (id) => {
  request
    .get('/sweet-api/play/video/click/' + id)
    .then((res) => {
      // debugger
      if (res.data.code == 1) {
        console.log('添加到主页成功', res.data)
      }else{
        console.log('添加到主页失败', res.msg)
      }
    })
    .catch((error) => {
      console.log('添加到主页失败', error)
    })
}
// 2.----字幕接口-----http://服务id:端口/video/vtt/{noteId}.vtt
const vttUrl = ref('')
const getVtt = () => {
  
  request
    .get('/sweet-api/video/vtt/' + route.query.id)
    .then((res) => {
      // debugger
      if(res.data.code==1){
        console.log('获取字幕成功', res.data)
        vttUrl.value = res.data.data
      }else{
        console.log('获取字幕失败', res.msg)
      }
      
    })
    .catch((error) => {
      console.log('获取字幕失败', error)
    })
    .finally(() => {
      init()
    })
}

// 4.----文章摘要接口-----
const getSummery = () => {
  request
    .get('/sweet-api/summery/query/' + route.query.id)
    .then((res) => {
      // debugger
      // console.log("获取文章摘要成功",res.data);
      if (res.data.code == 1) {
        
      }
    })
    .catch((error) => {
      console.log('获取文章摘要失败', error)
    })
}

let player
const currentTime = ref(-1)
const scrollbarRef = ref('')
const getHighLight = () => {
  let res = -1
  for (let i = 0; i < list.value.length; i++) {
    // debugger
    if (
      list.value[i].startTime <= currentTime.value * 1000 &&
      list.value[i].endTime > currentTime.value * 1000
    ) {
      // console.log(currentTime.value,list.value[i].startTime,list.value[i].endTime)
      res = i
      break
    }
  }
  return res
}

const init = () => {
  //2. 初始化视频播放器
  // debugger
  player = new Player({
    id: 'video-player',
    // url: videoSrc,
    // url:'http://10.31.3.212:81/record/www/2024/01/16/219b4534-2cbc-422c-8ba1-c1382d89f3ce.mp4',
    videoInit: {
        type: 'video/mp4', // 默认支持的视频格式
        hls: 'application/x-mpegURL', // 支持 HLS 格式
        flv: 'video/x-flv', // 支持 FLV 格式
        m4v: 'video/x-m4v', // 支持 m4v 格式 --测试ok
        avi: 'video/x-msvideo', // 支持 avi 格式
        // avi: 'video/avi', // 支持 avi 格式
        mov: 'video/quicktime', // 支持 mov 格式--测试ok
        wmv: 'video/x-ms-wmv', // 支持 wmv 格式
        // 可以继续添加其他视频格式的 MIME 类型
    },
    url: route.query.url,
    lang: 'zh-cn',
    volumn: 0.2,
    autoplay: false,
    poster: '',
    videoInit: true,
    textTrack: [
      {
        // src: "https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/byted-player-videos/1.0.0/textTrack-2.vtt",
        src: vttUrl.value,
        label: '开启',
        default: true,
        srclang: "zh",
      }
    ],
    // cssFullscreen: true,   // 页面中全屏
    playbackRate: [0.5, 0.75, 1, 1.5, 2], //倍速
    marginControls: true, //分别渲染控制栏(控制栏始终为黑色)和媒体元素
    initShow: true, //播放器初始化时就显示控制栏

    // videoInit: true,  //初始化首帧/该配置在移动端无效 | 与autoplay配置项不可同时设置为true
    closeInactive: false, //使播放器控制栏常驻不隐藏
    customConfig:{
      //自定义 快进 快退
      forward: 15, // 快进时间，单位为秒
      rewind: 15 // 快退时间，单位为秒
    },
  })
  // debugger
  // console.log(222222)
  // 监听视频播放时间
  player.on('timeupdate', () => {
    currentTime.value = player.currentTime
    // console.log('当前时间:', currentTime.value)
    let index = getHighLight()

    // console.log('index', index)
    // debugger
    if (index > -1) {
      // debugger
      if(iswheel1.value){
        // 添加滚轮事件监听器,取消滚动到可视区
        document.getElementById('scroll_' + list.value[index].id).scrollIntoView({ behavior: 'smooth',block: 'center'})
      }
      
    }
  })
  //监听播放错误
  player.on('error', () => {
    console.log('播放错误，请检查网络！')
   
       ElMessage({
          message: '播放错误，请检查网络！',
          type: 'error'
      })
  })
  //自定义快进 快退
  player.on('ready', () => {
    const forwardButton = document.createElement('img');
    forwardButton.src = forwordimg
    forwardButton.addEventListener('click', () => {
      player.currentTime += player.config.customConfig.forward;
    });

    const rewindButton = document.createElement('img');
    rewindButton.src = rewindimg;
    rewindButton.addEventListener('click', () => {
      player.currentTime -= player.config.customConfig.rewind;
    });

    const controls = player.controls;
    controls.appendChild(rewindButton);

    controls.appendChild(forwardButton);
  });
}

// ----页面滚乱----
const iswheel=ref(false)

const wheelFn=function(event) {
  // debugger
  console.log('监听滚轮滚动',event)
  // console.log(event.deltaY)
  if(event.deltaY > 0){
    iswheel.value=true
  }else{
    iswheel.value=false
  }
}
// 大滚轮
window.addEventListener('wheel', wheelFn)

// addwheel(window,wheelFn)

// function addwheel(obj,fn){
//     function wheel(ev){
//         var oEvent=ev||event;
//         var bDown=true;
//         if(oEvent.wheelDelta){
//             if(oEvent.wheelDelta<0){
//                 bDown=false;
//             }else{
//                 bDown=true;
//             }
//         }else{
//             if(oEvent.wheelDetail<0){
//                 bDown=true;
//             }else{
//                 bDown=false;
//             }
//         }
//         fn(bDown);
//         return false;
//         oEvent.preventDefault&&oEvent.preventDefault();
//     }
//     //判断是不是火狐
//     if(window.navigator.userAgent.toLowerCase().indexOf('firefox')!=-1){    
//         obj.addEventListener('DOMMouseScroll',wheel,false);//'DOMMouseScroll'只兼容火狐,必须用时间绑定；
//     }else{
//         obj.onmousewheel=wheel;
//     }
// }

// -----文字记录滚轮-----
const iswheel1=ref(true)
onMounted(() => {
  // 获取字幕接口
  getVtt()
  // 添加到主页接口
  addToMainPage(route.query.id)
  // 会议记录（转文字）接口
  getConferenceList()

  //文章摘要接口 
  // getSummery()
  // 通过scrollbar组件实例监听滚轮事件，有人为滚动，则取消自动滚动到可视区域
  scrollbarRef.value.wrapRef.addEventListener('wheel', function(event){
      // debugger
      console.log('监听文字列表滚动',event)
      event.stopPropagation(); // 阻止滚动事件冒泡到父元素
      iswheel1.value=false
  })
})

onBeforeUnmount(()=>{
  player.destroy();

  window.removeEventListener("wheel",wheelFn)
})

// 3.搜索框
const inputValue = ref(form.inputValue)
// 防抖
function debounce(func, wait, immediate) {
  let timeout
  return function () {
    let context = this
    let args = arguments
    if (timeout) {
      clearTimeout(timeout)
    }
    if (immediate) {
      let callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) {
        typeof func === 'function' && func.apply(context, args)
      }
    } else {
      timeout = setTimeout(() => {
        typeof func === 'function' && func.apply(context, args)
      }, wait)
    }
  }
}
// 搜索框输入内容变化，搜索
const inputChangeFn = () => {
  console.log(inputValue.value)
  count.value=0
  // debugger
  if (inputValue.value != '') {
  }
}
const inputChange = debounce(inputChangeFn, 500, false)

//4. 文字记录
const originList = ref([
  // {
  //   commentCount: 0,
  //   content:
  //     '想惩罚开除我给美丽的花，中国的山庄出发，开出无比美丽的花，中国的香山争霸，开出这一下美丽的花。',
  //   endTime: 182860,
  //   id: 61,
  //   startTime: 162580,
  //   time: '2024-01-17',
  //   userId: '4233dfdf4',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content: '。三牛牵马仲夏，你何时下山？记得带上卓玛拉，灰色帽檐下凹陷的脸颊',
  //   endTime: 121940,
  //   id: 62,
  //   startTime: 101620,
  //   time: '2024-01-17',
  //   userId: '4233dfdf4',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content: '住在西藏的某个地方，就这样栖息在山顶上。阿刁',
  //   endTime: 40660,
  //   id: 63,
  //   startTime: 20500,
  //   time: '2024-01-17',
  //   userId: '4233dfdf4',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content: '平凡却不甘平凡的溃败，你是阿刁，你是自由的鸟',
  //   endTime: 243540,
  //   id: 64,
  //   startTime: 223220,
  //   time: '2024-01-17',
  //   userId: '4233dfdf4',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content: '大昭寺门前铺满阳光，一壶甜茶，我们聊着过往',
  //   endTime: 60940,
  //   id: 65,
  //   startTime: 40660,
  //   time: '2024-01-17',
  //   userId: '4233dfdf4',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content: '爱情是粒悲伤的种子，你是一棵树，你永远都不会哭',
  //   endTime: 303610,
  //   id: 66,
  //   startTime: 283980,
  //   time: '2024-01-17',
  //   userId: '4233dfdf4',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content: '勇敢的溃败，你是阿刁。',
  //   endTime: 283980,
  //   id: 67,
  //   startTime: 263700,
  //   time: '2024-01-17',
  //   userName: '李四',
  //   videoId: 244
  // },
  // {
  //   commentCount: 0,
  //   content:
  //     '，也要追。过坷的路途，漫漫的脚步婆娑，慢慢的字迹斑驳，我着一丝痕迹都不能留在这里，我还是不会，因为同样情习惯生活，总是',
  //   endTime: 162580,
  //   id: 68,
  //   startTime: 142260,
  //   time: '2024-01-17',
  //   userName: '李四',
  //   videoId: 244
  // },
])
const count =ref(0)
const list = computed(() => {
  // debugger
  let arr = []
  if (inputValue.value) {
    for (let i = 0; i < originList.value.length; i++) {
      let item = JSON.parse(JSON.stringify(originList.value[i]))
      if (item.content.indexOf(inputValue.value) > -1) {
        let reg = new RegExp(inputValue.value, 'g')
        //通过正则匹配，将搜索词替换为高亮
        item.content = item.content.replace(
          reg,
          `<span style='background-color: #fff67a;
          color:#333;' class="search">${inputValue.value}</span>`
        )
        //通过match(reg) 计算正则匹配数量，结果为数组
        let matches=item.content.match(reg);
        
        count.value=count.value+(matches ? matches.length : 0)
      }
      arr.push(item)
    }
  } else {
    arr = [...originList.value]
  }

  return arr
})


// 根据音视频时长毫秒数，转换成对应的时分秒
const getHMS = (times) => {
  let time = times / 1000
  const hour = parseInt(time / 3600) < 10 ? '0' + parseInt(time / 3600) : parseInt(time / 3600)
  const min =
    parseInt((time % 3600) / 60) < 10
      ? '0' + parseInt((time % 3600) / 60)
      : parseInt((time % 3600) / 60)
  const sec =
    parseInt((time % 3600) % 60) < 10
      ? '0' + parseInt((time % 3600) % 60)
      : parseInt((time % 3600) % 60)
  return hour + ':' + min + ':' + sec
}

// 点击文字记录 反向定位视频
const reversePosition = (item) => {
  player.currentTime = (item.startTime / 1000).toFixed(6)
  player.play()
}



</script>
<style lang="less" scoped>
.videoPage {
  margin: 0;
  height: 100%;
  display: flex;
  flex-direction: column;

  // 1.音频播放
  .videoPlayer {
    width: 750px;
    height: 422px;
    margin: 0 auto;
    padding-top: 4px;
    padding-bottom: 4px;
    display: flex;
    flex: none;

    :deep(.xgplayer) {
      width: 100% !important;
      height: 100% !important;
      // margin: 4px auto !important;
      //视频控制栏
      .xgplayer-controls {
        height: 58px;
        background-color: rgba(64, 64, 64, 1);
        .xgplayer-progress {
          top: 0px;
        }
        .xgplayer-play {
          margin-top: 12px;
          order: 0;
        }
        .xgplayer-time {
          margin-top: 12px;
          order: 2;
        }
        .xgplayer-volume {
          margin-top: 12px;
          order: 4;
        }
        .xgplayer-texttrack {
          margin-top: -107px;
          order: 8;
          .name {
            background-color: transparent;
            color: rgba(255, 255, 255, 1);
          }
        }
        .xgplayer-playbackrate {
          margin-top: -107px;
          order: 7;
          .name {
            background-color: transparent;
            color: rgba(255, 255, 255, 1);
          }
        }
        .xgplayer-fullscreen {
          margin-top: 13px;
          order: 13;
        }
        &>img{
          width: 18px;
          height: 18px;
          margin-top: 24px;
        }
        &>img:nth-child(8){
          margin-right: 6px;
        }
      }
      .xg-text-track {
        width: 100% !important;
        font-size: 18px !important;
        position: absolute !important;
        left: 0px !important;
        bottom: 60px !important;
        text-align: center;
        // 字幕动画
        transition: bottom 0.3s ease;

        .text-track-double{
          text-shadow: 1px 1px 3px #000000;
        }
      } 
    }

  }

  .videoPlayerSmall{
    width: 400px;
    height: 222px;
    display: flex;
    flex: none;
    margin: 0 auto;
    :deep(.xgplayer) {
        .xg-text-track {
        
         font-size: 12px !important;
        }
      }
  }

  // 3.文字记录/搜索
  .top {
    height: 77px;
    border-top: 1px solid rgba(217, 217, 217, 1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: none;
    .search {
      width: 240px;
      height: 34px;
      border-radius: 2px;
      color: rgba(206, 206, 206, 1);
      font-size: 14px;
      text-align: left;
      font-family: Roboto;
    }
  }

  // 4.文字记录信息
  .transcriptionRecord {
    display: flex;
    flex-direction: column;
    flex: 1;
    // overflow: hidden;
    .recordinfo {
      margin-bottom: 10px;
      display: flex;
      justify-content: flex-start;
      //1.左侧
      .left {
        width: 34px;
        height: 34px;
        line-height: 34px;
        border-radius: 50%;
        background: linear-gradient(180deg, rgba(92, 219, 211, 1) 0%, rgba(19, 194, 194, 1) 100%);
        color: rgba(255, 255, 255, 1);
        font-size: 12px;
        margin-right: 8px;
        text-align: center;
        font-family: Microsoft Yahei;
        flex: none;
      }
      // 2.右侧
      .right {
        .rightTop {
          & > span {
            width: 28px;
            height: 20px;
            color: rgba(145, 145, 145, 1);
            font-size: 14px;
            text-align: left;
            font-family: PingFangSC-regular;
            margin-right: 4px;
          }
          & > span:nth-child(2) {
            font-size: 12px;
          }
        }
        .rightContent {
          // height: 48px;
          color: rgba(64, 64, 64, 1);
          font-size: 14px;
          text-align: left;
          font-family: SourceHanSansSC-regular;
        }
        .active {
          background-color: #096dd9;
          color: #fff;
        }
      }
    }
  }
}
</style>
